﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Mvc;
using System.Web.Routing;
using System.Web;
using Microsoft.Practices.Unity;
using HMIS.MVC.CommonSupport;
using HMIS.FrameWork.Repository.NHb;
using HMIS.Infrastructure.Facade.Authority;
using Quartz;

namespace HMIS.MVC
{
	public class DemoHISApplication : HttpApplication
	{
		protected static readonly log4net.ILog clog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
		IScheduler sched;

		protected virtual void OnStart()
		{
			try
			{
				initContainer();
				RegisterRoutes(RouteTable.Routes);
				initSessionBuilder();
				initApplicationCache();
			}
			catch (Exception ee)
			{
				clog.Error(ee);
			}
		}
		//应用程序开始的时候初始的缓存
		private void initApplicationCache()
		{
			ContainerFactory.GetContainer().Resolve<IAuthorityFacade>().GetAllActionPermission();//所有被维护的Action权限
		}

		private void initSessionBuilder()
		{
			SessionBuilder.sessionStorage = new HttpSessionStorage();
		}

		private void initContainer()
		{
			ControllerBuilder.Current.SetControllerFactory(new UnityControllerFactory(ContainerFactory.GetContainer()));
		}

		public static void RegisterRoutes(RouteCollection routes)
		{
			routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

			routes.MapRoute(
				"Default",                                              // Route name
				"{controller}/{action}/{id}",                           // URL with parameters
				new { controller = "Main", action = "Login", id = "" }  // Parameter defaults
			);

		}

		protected void Application_Start()
		{
			log4net.Config.XmlConfigurator.Configure(new System.IO.FileInfo("log4net.cfg.xml"));
			OnStart();
			//quartz
			ISchedulerFactory sf = new Quartz.Impl.StdSchedulerFactory();
			sched = sf.GetScheduler();
			sched.Start();
		}

		protected void Application_End(object sender, EventArgs e)
		{
			// 在应用程序关闭时运行的代码
			if (sched != null)
			{
				sched.Shutdown(true);
			}
		}

	}
}
